package com.example.venadaoa.net;

import android.support.annotation.NonNull;
import android.util.Log;

import com.android.internal.http.multipart.FilePart;
import com.android.internal.http.multipart.MultipartEntity;
import com.android.internal.http.multipart.Part;
import com.android.internal.http.multipart.StringPart;
import com.duowan.mobile.netroid.AuthFailureError;
import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetworkResponse;
import com.duowan.mobile.netroid.Request;
import com.duowan.mobile.netroid.Response;
import com.duowan.mobile.netroid.request.StringRequest;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import static android.R.attr.path;
import static com.example.venadaoa.R.drawable.file;

/**
 * Created by weng on 2017/7/13.
 */

public class UploadRequest extends StringRequest {

    private File file;
    private Part[] parts;

    public UploadRequest(int method, String url, ArrayList<String> listPath, Listener<String> listener) {
        super(method, url, listener);
        parts = new Part[listPath.size()];
        for (int i = 0; i < listPath.size(); i++) {
            try {
                parts[i] = new FilePart("file" + i, new File(listPath.get(i)));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public UploadRequest(int method, String url, String path, Listener<String> listener) {
        super(method, url, listener);
        this.file = new File(path);
        try {
            parts = new Part[]{new FilePart("file", file)};
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    @Override
    public String getBodyContentType() {
        return "multipart/form-data; boundary=" + Part.getBoundary();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            Part.sendParts(baos, parts);
        } catch (IOException e) {
            e.getStackTrace();
        }
        return baos.toByteArray();
    }
}
